$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPTOOLOPE : "XPTOOLOPE" ,
        T_XPLSTEQP  : "XPLSTEQP"  ,
        T_XPAPLYWO  : "XPAPLYWO"  ,
        T_XPIWIPEQ  : "XPIWIPEQ"  ,
        T_XPMOVEIN  : "XPMOVEIN"  ,
        T_XPBISOPE  : "XPBISOPE"
    };
    var domObj = {
			$window : $(window),
			$boxInfoDiv : $("#boxInfoDiv"),
			$boxInfoGrd : $("#boxInfoGrd")
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                  : $(window)             ,
        opeSelect          : $("#opeSelect")       ,
        woIdSelect         : $("#woIdSelect")      ,
        lotIdInput         : $("#lotIdInput")      ,
        boxIdInput         : $("#boxIdInput")      ,
//        userIdInput        : $("#userIdInput")     ,
        from_thicknessTxt  : $("#from_thicknessTxt"),
        to_thicknessTxt    : $("#to_thicknessTxt")  ,
        woPlnQtyTxt    : $("#woPlnQtyTxt")  ,
        woRlQtyTxt     : $("#woRlQtyTxt")   ,
        woLevQtyTxt    : $("#woLevQtyTxt")  ,

        mainGrd   :{
            grdId     : $("#boxInfoGrd")   ,
            grdPgText : "#boxInfoPg"       ,
            fatherDiv : $("#boxInfoDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1 : $("#f1_btn"),
        f8 : $("#f8_btn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.lotIdInput.val("");
            controlsQuery.boxIdInput.val("");
            controlsQuery.from_thicknessTxt.val("");
            controlsQuery.to_thicknessTxt.val("");
            controlsQuery.woPlnQtyTxt.val("");
            controlsQuery.woRlQtyTxt.val("");
            controlsQuery.woLevQtyTxt.val("");
        },
        setOpeSelectDate : function(dataCnt, arr, selVal, selVal2, selTxt, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
       //         if( arr.hasOwnProperty(selVal) &&
      //              arr[selVal] != "JB-01"){
                    queryObj.append("<option value="+ arr[selVal] + "@" + arr[selVal2] + ">"+ arr[selTxt] +"</option>");
       //         }
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
          //          if( arr[i].hasOwnProperty(selVal) &&
         //               arr[i][selVal] != "JB-01"){
                        queryObj.append("<option value="+ arr[i][selVal] + "@" + arr[i][selVal2] + ">"+ arr[i][selTxt] +"</option>");
         //           }
                }
            }
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
        },
        iniOpeSelect : function(){
            var inObj, outObj;

            inObj = {
                trx_id      : VAL.T_XPBISOPE,
                action_flg  : 'L'
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                toolFunc.setOpeSelectDate(outObj.tbl_cnt, outObj.oary, "ope_id", "ope_ver", "ope_dsc", controlsQuery.opeSelect);
            }
        },
        iniWoIdSelect : function(){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                iary : {
                    wo_stat : "WAIT"
                }
            };

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", "wo_id", "#woIdSelect", true);
            }
        },
        getWoInfoFunc : function(){
            var wo_id,
                inObj,
                outObj;

            controlsQuery.from_thicknessTxt.val("");
            controlsQuery.to_thicknessTxt.val("");

            wo_id = controlsQuery.woIdSelect.val().trim();
            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                iary : {
                    wo_id     : wo_id,
                    mtrl_cate : "SHMT"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                controlsQuery.from_thicknessTxt.val(outObj.oary.from_thickness);
                controlsQuery.to_thicknessTxt.val(outObj.oary.to_thickness);
                controlsQuery.woPlnQtyTxt.val(outObj.oary.pln_prd_qty);
                controlsQuery.woRlQtyTxt.val(outObj.oary.rl_prd_qty);
                controlsQuery.woLevQtyTxt.val( parseInt(outObj.oary.pln_prd_qty,10) - parseInt(outObj.oary.rl_prd_qty,10) );
            }
            return true;
        }
    }; 

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        f1_func : function(){
            var inObj,
                outObj,
                ope_id,
                ope_ver,
                opeIndex,
                lot_id,
                box_id,
                wo_id;

            if(!$.trim(controlsQuery.opeSelect.val())){
                return false;
            }

            opeIndex = controlsQuery.opeSelect.val().indexOf("@");
            ope_id = controlsQuery.opeSelect.val().substr(0, opeIndex);
            ope_ver = controlsQuery.opeSelect.val().substr(opeIndex+1);

            wo_id = controlsQuery.woIdSelect.val().trim();
            lot_id = controlsQuery.lotIdInput.val().trim();
            box_id = controlsQuery.boxIdInput.val().trim();

            inObj = {
                trx_id      : VAL.T_XPIWIPEQ,
                action_flg  : "I"           ,
                cr_ope_id   : ope_id,
                cr_ope_ver  : ope_ver
            };

            if(wo_id){
                inObj.wo_id = wo_id;
            }
            if(lot_id){
                inObj.lot_id = lot_id;
            }
            if(box_id){
                inObj.box_id = box_id;
            }
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary, "#boxInfoGrd");
            }
        },
        //Move in
        f8_func : function(){
            var iRow,
                selectRowIds,
                selectRowIdsLen,
                selectRow,
                box_id,
                ope_id,
                ope_ver,
                opeIndex,
//                user_id,
                movein_rc,
                inObj,
                outObj;

            if(!$.trim(controlsQuery.opeSelect.val())){
                return false;
            }

            opeIndex = controlsQuery.opeSelect.val().indexOf("@");
            ope_id = controlsQuery.opeSelect.val().substr(0, opeIndex);
            ope_ver = controlsQuery.opeSelect.val().substr(opeIndex+1);

//            user_id = $.trim(controlsQuery.userIdInput.val());
//            if(!user_id){
//                showErrorDialog("","请输入入账人员工号！");
//                return false;
//            }

            selectRowIds = controlsQuery.mainGrd.grdId.jqGrid('getGridParam','selarrrow');
            selectRowIdsLen = selectRowIds.length;
            if( selectRowIdsLen <= 0 ){
                showErrorDialog("01","请选择要释放的箱号！");
                return false;
            }

            for( iRow = 0; iRow<selectRowIdsLen; iRow++){
                selectRow = controlsQuery.mainGrd.grdId.jqGrid("getRowData", selectRowIds[iRow]);

                box_id = selectRow['box_id'];
                if(!box_id){
                    showErrorDialog("02","请选择要释放的箱号！");
                    return false;
                }

                movein_rc = selectRow['rc'];
                if("Y" === movein_rc){
                    showErrorDialog("", box_id + "已经入账，请勿重复操作！");
                    return false;
                }

                if (VAL.EVT_USER == "" || VAL.EVT_USER == null || VAL.EVT_USER == undefined){
                	showErrorDialog("","请重新登录！");
                	return false;
                }
                
                inObj = {
                    trx_id     : VAL.T_XPMOVEIN,
                    evt_usr    : VAL.EVT_USER  ,
                    box_id     : box_id        ,
                    cr_ope_id  : ope_id        ,
                    cr_ope_ver : ope_ver
                };
                outObj = comTrxSubSendPostJson(inObj);
                if(outObj.rtn_code == VAL.NORMAL) {
                    selectRow['rc'] = "Y";
                    controlsQuery.mainGrd.grdId.jqGrid("setRowData", selectRowIds[iRow], selectRow);
                }else{
                    selectRow['rc'] = "N";
                    controlsQuery.mainGrd.grdId.jqGrid("setRowData", selectRowIds[iRow], selectRow);
                }
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
        btnQuery.f8.click(function(){
            btnFunc.f8_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'rc',        index: 'rc',       label: RELEASE_RESULT_TAG    , width: RC_CLM},
            {name: 'isJumpOpe', index: 'isJumpOpe',label: '返品'    , width: REWK_FLAG_CLM},
            {name: 'lot_id',    index: 'lot_id',   label: LOT_ID_TAG  , width: LOT_ID_CLM},
            {name: 'box_id',    index: 'box_id',   label: CRR_ID_TAG  , width: BOX_ID_CLM},

            {name: 'mtrl_prod_id',   index: 'mtrl_prod_id',   label: MTRL_PROD_ID_TAG   , width: MTRL_PROD_ID_CLM},
//            {name: 'mdl_id_fk',      index: 'mdl_id_fk',      label: TO_MTRL_ID_TAG     , width: 100},
            {name: 'mdl_id',         index: 'mdl_id',         label: MDL_ID_TAG         , width: MDL_ID_CLM},
            {name: 'fm_mdl_id_fk',   index: 'fm_mdl_id_fk',   label: FM_MDL_ID_TAG      , width: MDL_ID_CLM},
            {name: 'cut_mdl_id_fk',  index: 'cut_mdl_id_fk',  label: CUT_MDL_ID_TAG     , width: MDL_ID_CLM},

            {name: 'mode_cnt',     index: 'mode_cnt',     label: MODE_CNT_TAG      , width: MODE_CNT_CLM},
            {name: 'ok_grade_cnt', index: 'ok_grade_cnt', label: OK_CNT_TAG        , width: QTY_CLM},
            {name: 'ng_grade_cnt', index: 'ng_grade_cnt', label: NG_CNT_TAG        , width: QTY_CLM},
            {name: 'gk_grade_cnt', index: 'gk_grade_cnt', label: GRADE_CONTROL_TAG , width: QTY_CLM},
            {name: 'lz_grade_cnt', index: 'lz_grade_cnt', label: GRADE_SCRP_TAG    , width: QTY_CLM},

            {name: 'from_thickness', index: 'from_thickness', label: FROM_THICKNESS_TAG , width: QTY_CLM},
            {name: 'to_thickness',   index: 'to_thickness',   label: TO_THICKNESS_TAG   , width: QTY_CLM},

            {name: 'qty',       index: 'qty',      label: QTY_TAG     , width: QTY_CLM},
            {name: 'path_id'  , index: 'path_id',  label: PATH_ID_TAG , width: PATH_ID_CLM},
            {name: 'ope_id'   , index: 'ope_id',   label: OPE_ID_TAG  , width: OPE_ID_CLM},
            {name: 'wo_id'   ,  index: 'wo_id',    label: WO_ID_TAG   , width: WO_ID_CLM},
            {name: 'priority',  index: 'priority', label: PRTY_TAG    , width: PRIORITY_CLM}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
//            height:300,
            width:domObj.$boxInfoDiv.width(),
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            multiselect : true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM
        });
    };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.f1.click();
                return false;
            }else if(event.keyCode == F2_KEY){
//                btnQuery.f8.click();
                return false;
            }

            return true;
        };
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        controlsQuery.woIdSelect.change(function(){
            toolFunc.getWoInfoFunc();
        });

        shortCutKeyBind();
    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();

        //Tool info
        toolFunc.iniOpeSelect();

        //Wo info
        toolFunc.iniWoIdSelect();

    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();

        toolFunc.resetJqgrid();

        iniContorlData();
    };

    initializationFunc();
    
    function resizeFnc(){        
    	comResize(controlsQuery.W,controlsQuery.mainGrd.fatherDiv,controlsQuery.mainGrd.grdId);
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	});  
    
});

